import {Injectable} from '@angular/core';
import {FormControl, FormGroup} from '@angular/forms';

@Injectable()
export class FormCommonService {
  arr = [];

  constructor() {
  }

  // 通用的重置表单
  resetForm(form: FormGroup) {
    form.reset();
    for (const key in form.controls) {
      form.controls[key].markAsPristine();
    }
  }

  // 通用拼装form对象方法(主要用在提交表单) ->{ account: this.getFormControlThree('account').value }
  getCommonFormObject(formName, ...keys) {
    return Object.assign({}, ...keys.map(v => {
      return {
        [v]: formName.controls[v].value
      };
    }));
  }

  getCommonFormObjectBoolean(formName, ...keys) {
    return Object.assign({}, ...keys.map(v => {
      return {
        [v]: formName.controls[v].value ? 1 : 0
      };
    }));
  }

  getCommonObject(formName, ...keys) {
    return Object.assign({}, ...keys.map(v => {
      return {
        [v]: {id: formName.controls[v].value}
      };
    }));
  }

  // 通用响应式表单设置值方法(主要用在回显表单)
  commonSetValue(formName, data, ...keys) {
    keys.forEach(v => formName.controls[v].setValue(data['data'][v]));
  }

  // 通用的表单获取值方法
  commonGetControl(formName, key) {
    return formName.controls[key];
  }

  // 换行符转译
  lineBreaksEscape(original) {
    return original.replace(/\n/g, '<br>');
  }

  // // 校验输入是否为空格
  // trimValidator = (control: FormControl): any => {
  //   if (!control.value || control.value.trim() === '') {
  //     return {error: true, trimError: true};
  //   }
  //   return null;
  // }
  trimValidator = (control: FormControl): any => {
    if (control.value) {
      this.arr = control.value.split('');
    } else {
      return null;
    }
    for (let i = 0; i < this.arr.length; i++) {
      if (!control.value || control.value.trim() === '' || this.arr[i] === ' ') {
        return {error: true, trimError: true};
      }
    }
    return null;
  }
  // 校验多行文本是否输入为空格
  myTrimValidator = (control: FormControl): any => {
    if (control.value && control.value !== '' && control.value.trim() === '') {
      return {error: true, trimError: true};
    }
    return null;
  }
  // 日期范围选择器判断为空校验
  dateRangeValidator = (control: FormControl): any => {
    if (control.value && control.value[0] && control.value[1]) {
      return null;
    }
    return {error: true, dateRangeError: true};
  }

  /**
   * 设置日期选择器最大日期范围
   * */
  setMaxDate(current: Date): boolean {
    return current && current.getTime() > Date.now();
  }

  dateValidator = (control: FormControl): any => {
    if (control.value) {
      return null;
    }
    return {error: true, dateError: true};
  }

  // 通用的让弹框滚动条回到0
  scrollTop() {
    const modalBody = document.querySelectorAll('.modal-content .modal-body');
    for (let i = 0; i < modalBody.length; i++) {
      modalBody[i].scrollTop = 0;
    }
  }

}
